package NIO.blocking;
/*
 * @Author  Wrial
 * @Date Created in 23:19 2020/4/8
 * @Description
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class StreamClient {
    public static void main(String[] args) throws IOException {
        new StreamClient("localhost", 8090).sendMsg();
    }

    private String ip;
    private int port;
    Socket socket;

    public StreamClient(String ip, int port) throws IOException {
        this.ip = ip;
        this.port = port;
        init();
    }

    private void init() throws IOException {
        socket = new Socket(ip, port);
        System.out.println("client  init - ->" + port);
    }

    private PrintWriter getWriter(Socket socket) throws IOException {
        // true是自动刷新
        return new PrintWriter(socket.getOutputStream(),true);
    }

    private BufferedReader getReader(Socket socket) throws IOException {
        return new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }

    private void sendMsg() throws IOException {
        BufferedReader bufferedReader = getReader(socket);
        PrintWriter printWriter = getWriter(socket);

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        String sendMsg;
        while ((sendMsg = reader.readLine())!=null){
            printWriter.println(sendMsg);
            System.out.println(bufferedReader.readLine());
            if (sendMsg.equals("end")){
                System.out.println("end");
                break;
            }
        }
        if (socket!=null) socket.close();
    }





}
